package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.PackTemplet;
import com.scs.application.modules.base.entity.PackTempletItem;
import com.scs.application.modules.base.mapper.PackTempletItemMapper;
import com.scs.application.modules.base.mapper.PackTempletMapper;
import com.scs.application.modules.base.service.PackTempletService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class PackTempletServiceImpl extends BaseServiceImpl<PackTempletMapper, PackTemplet> implements PackTempletService {

    @Autowired
    private PackTempletItemMapper packTempletItemMapper;

    @Override
    public boolean saveOrUpdate(PackTemplet entity) {
        int count = this.count(Wrappers.<PackTemplet>query()
                .eq("name", entity.getName())
                .eq("pack_type", entity.getPackType())
                .ne("id", entity.getId()));

        if (count > 0) {
            throw new BusinessException("模板名称不允许重复");
        }
        if(StringUtils.isBlank(entity.getSupplierId()) || "0".equals(entity.getSupplierId())) { entity.setSupplierId(null).setSupplierName(null); }
        if(StringUtils.isBlank(entity.getDeptId()) || "0".equals(entity.getDeptId())) { entity.setDeptId(null).setDeptName(null); }
        boolean success = super.saveOrUpdate(entity);
        return success;
    }


    @Override
    public Page<Map> pageForSelect(QueryContext context, Map<String, Object> userParam) {
        return this.baseMapper.pageForSelect(context.getPage(), context.getWrapper(), context.getParams(),userParam);
    }


    @Override
    public void calculatePackAmount(List<String> idList) {
        this.baseMapper.calculatePackAmount(idList);
    }

    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<PackTempletItem> packTempletItems = packTempletItemMapper.selectList(Wrappers.<PackTempletItem>query().in("pack_templet_id", idList));
        if (CollectionUtils.isNotEmpty(packTempletItems)) {
            packTempletItemMapper.deleteBatchIds(packTempletItems.stream().map(PackTempletItem::getId).collect(Collectors.toList()));
        }
        return super.removeCascadeByIds(idList);
    }
}
